from nonebot import on_regex, on_command, logger, get_driver
from nonebot.params import RegexDict
from nonebot.permission import SUPERUSER
from nonebot.adapters.onebot.v11.message import MessageSegment

from .download import download_resources
from .config import genshin_resource_config
from .draw import draw

driver = get_driver()
find_resources = on_regex(r"#?(?P<name>.+)?在(?P<map_name>.+)?哪")
update_resources = on_command("地图资源更新", block=True, permission=SUPERUSER)


@find_resources.handle()
async def _(res: dict = RegexDict()):
    if not res["name"]:
        await find_resources.finish("请指定物品！")

    resource_list = genshin_resource_config.resource_alias.get(res["name"]) or res["name"].split(" ")
    if isinstance(resource_list, str):
        resource_list = [resource_list]

    if res["map_name"] in ["渊下宫"]:
        map_id = "7"
    elif res["map_name"] in ["层岩", "层岩巨渊"]:
        map_id = "9"
    elif res["map_name"] in ["海岛", "金苹果", "金苹果群岛"]:
        map_id = "12"
    else:
        map_id = "2"

    try:
        img, msg = await draw(map_id, resource_list)
        await find_resources.send(MessageSegment.image(img) + msg)
    except Exception as e:
        logger.error(e)


@update_resources.handle()
async def _():
    await download_resources(True)


driver.on_startup(download_resources)
